import WxRequest from '@/utils/request'
import {
  toast,
  model
} from '@/utils/extend'
import {
  getStorage,
  removeStorage
} from '@/utils/storage'

import {
  env
} from '@/utils/env'
const appInstance = getApp()

const instance = new WxRequest({
  baseURL: env.baseURL,
  timeout: 15000
})

instance.interceptors.request = (config) => {
  const token = getStorage('token')
  if (token) {
    config.header['satoken'] = token
  } else {
    config.header['satoken'] = ''
  }
  return config
}

instance.interceptors.response = async (response) => {
  const {
    isSuccess,
    data
  } = response
  if (!isSuccess) {
    clearInterval(appInstance.globalData.pollingInterval)
    toast({
      title: '网络异常请重试',
      icon: 'error'
    })
    return Promise.reject(response)
  }
  switch (data.code) {
    case 200:
      return data
    case 401:
      clearInterval(appInstance.globalData.pollingInterval)
      wx.navigateTo({
        url: '/pages/login/login',
      })
      return Promise.reject(response)
    case 403:
      const res = await model({
        content: '鉴权失败，请重新登录',
        showCancel: false
      })
      if (res) {
        removeStorage('token')
        removeStorage('userInfo')
        clearInterval(appInstance.globalData.pollingInterval)
        wx.navigateTo({
          url: '/pages/login/login',
        })
      }
      return Promise.reject(response)
    case 500:
      toast({
        title: '操作异常' + (data.msg ? (',' + data.msg) : ""),
      })
      return Promise.reject(response)
    default:
      toast({
        title: '程序出现异常'
      })
      return Promise.reject(response)
  }
}

export default instance